<?php
// +----------------------------------------------------------------------
// | XiaMiCMF - 代码如诗
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://shujuwajue.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小虾米 <509129@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Model;

use Common\Model\CommonModel;

class AdminModel extends CommonModel
{
    //默认的超级管理员的admin_id主键值
    const DEFAULT_ADMIN      = 1;
    const DEFAULT_ADMIN_ROLE = 1;

    protected $_validate = array(
        //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
        array('username', 'require', '用户名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
        array('username', '', '用户名已经存在', self::VALUE_VALIDATE,'unique', self::MODEL_BOTH),
        array('password', 'require', '密码不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
        array('password', 'require', '密码不能为空', self::EXISTS_VALIDATE, 'regex', self::MODEL_UPDATE),
        array('mobile', '', '手机号已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_BOTH),
        array('mobile', 'x_isMobile', '手机格式不正确', self::VALUE_VALIDATE, 'function'), // 自定义函数验证手机格式
        array('email', '', '邮箱帐号已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_BOTH),
        array('email', 'email', '邮箱格式不正确', self::VALUE_VALIDATE, '', self::MODEL_BOTH),
    );

    protected $_auto = array(
        //array(完成字段1,完成规则,[完成条件,附加规则]),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('create_ip','get_client_ip', self::MODEL_INSERT, 'function'),
    );

    public function getAdminByUsername($username) {
        $data = $this->find(array('where' => array('username' => $username)));
        if(x_get_admin_id() == self::DEFAULT_ADMIN) {
            return $data;
        }
        return $this->_format($data);
    }

    public function _format($data) {

        $roles = D('AuthRole')->fetchAll();

        $role_ids = array();
        if (!empty($data['admin_id'])) {
            unset($data['password']);
            $role_ids = M('AuthRoleUser')->where(array('admin_id' => $data['admin_id']))
                ->getField("role_id", true);
        }

        if (!empty($role_ids)) {
            $data['role_ids'] = $role_ids;
            foreach ($role_ids as $role_id) {
                $data['role_name'] .= (empty($data['role_name']) ?
                    $roles[$role_id]['role_name'] : ',' . $roles[$role_id]['role_name']);

            }
        }

        return $data;
    }

    protected function _before_write(&$data) {
        if (!empty($data['password']) && strlen($data['password']) < 25) {
            $data['password'] = x_encrypt_password($data['password']);
        }
    }
}

?>